package com.yuyou.weixin.service.impl;


import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;

import com.yuyou.weixin.cache.GuavaCacheUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sun.misc.BASE64Encoder;

import com.google.code.kaptcha.Producer;
import com.yuyou.weixin.bean.ResBoolSimpleInfo;
import com.yuyou.weixin.message.CaptchaMess;
import com.yuyou.weixin.service.ICaptchaService;
import com.yuyou.weixin.util.TokenUtil;
import com.yuyou.weixin.vo.resp.RespCaptcha;


@Service
public class CaptchaServiceImpl implements ICaptchaService {
	
	@Autowired
	private Producer producer;
	
	public RespCaptcha generCaptcha() throws Exception{
		RespCaptcha res=new RespCaptcha();
		
        // 生成文字验证码   	  
        String text = producer.createText();  
        // 生成图片验证码  
        ByteArrayOutputStream outputStream = null;   
        BufferedImage image = producer.createImage(text);       
        outputStream = new ByteArrayOutputStream();    
        ImageIO.write(image, "jpg", outputStream);             
        // 对字节数组Base64编码    
        BASE64Encoder encoder = new BASE64Encoder();              
        // 生成captcha的token  
        String token=TokenUtil.GenerateToken();
        res.setToken(token);
        res.setImg(encoder.encode(outputStream.toByteArray()));
		
        //session TODO
        GuavaCacheUtil.put(token,text);
        System.out.println(text+"--"+token+"--"+GuavaCacheUtil.get(token));
//        stringRedisTemplate.opsForValue().set(token, text, 10, TimeUnit.MINUTES);
		
		return res;
	}
	

	@Override
	public ResBoolSimpleInfo<String> verifyCode(String token,String text) {
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
        if (StringUtils.isEmpty(token)) {        
        	res.setSuccess(false);
        	res.setMessage(CaptchaMess.ERR_CAPTCHA_EMPTY);
        }
        else if (StringUtils.isEmpty(text)) {   
        	res.setSuccess(false);
        	res.setMessage(CaptchaMess.ERR_CAPTCHA_EMPTY);
        }else{
            //session TODO
            String val = GuavaCacheUtil.get(token);
//            String val = (String) stringRedisTemplate.opsForValue().get(token);
            if (val == null || !val.equalsIgnoreCase(text)) {
            	res.setSuccess(false);
            	res.setMessage(CaptchaMess.ERR_CAPTCHA_EXPIRE);
            }else{
            	res.setSuccess(true);
            }
        }
        //session TODO
//        //清除
        if(!StringUtils.isEmpty(token)){
            GuavaCacheUtil.del(token);
        }
        return res;
	}

}
